package com.shuangdj.databinding.BindAdapter;

import android.databinding.BindingAdapter;
import android.databinding.InverseBindingAdapter;
import android.databinding.InverseBindingListener;
import android.databinding.adapters.ListenerUtil;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.widget.ListView;

import com.shuangdj.databinding.R;
import com.shuangdj.databinding.adapter.TestAdapter;
import com.shuangdj.databinding.bean.TestModel;

import java.util.List;

/**
 * Created by linxiaoke on 17/4/11.
 */

public class SwipeRefreshLayoutBindAdapter {

    @BindingAdapter("setTestAdapter")
    public static void setList(ListView list, List<TestModel> testModels) {
        TestAdapter tAdapter = (TestAdapter) list.getAdapter();
        Log.i("sss", "ssss");
        if (tAdapter == null) {
            tAdapter = new TestAdapter(list.getContext(), testModels);
            list.setAdapter(tAdapter);
        } else {
            tAdapter.setData(testModels);
        }
    }


    @BindingAdapter("refreshing")
    public static void setRefreshing(SwipeRefreshLayout view, boolean refreshing) {
        Log.i("sdj", "setRefreshing   view.isRefreshing():" + view.isRefreshing() + "    refreshing:" + refreshing);
        if (refreshing != view.isRefreshing()) {
            view.setRefreshing(refreshing);
        }
    }

    @InverseBindingAdapter(attribute = "refreshing", event = "refreshingAttrChanged")
    public static boolean isRefreshing(SwipeRefreshLayout view) {
        Log.i("sdj", "isRefreshing:" + view.isRefreshing());
        return view.isRefreshing();
    }

    @BindingAdapter(value = {"onRefreshListener", "refreshingAttrChanged"}, requireAll = false)
    public static void setOnRefreshListener(final SwipeRefreshLayout view,
                                            final SwipeRefreshLayout.OnRefreshListener listener,
                                            final InverseBindingListener refreshingAttrChanged) {

        SwipeRefreshLayout.OnRefreshListener newValue = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (listener != null) {
                    listener.onRefresh();
                }
                if (refreshingAttrChanged != null) {
                    refreshingAttrChanged.onChange();
                }
            }
        };

        SwipeRefreshLayout.OnRefreshListener oldValue = ListenerUtil.trackListener(view, newValue, R.id.swiperefreshlayout);
        if (oldValue != null) {
            view.setOnRefreshListener(null);
        }
        view.setOnRefreshListener(newValue);
    }

}
